/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.AjaxDAO;
import dao.ChiTietDauGiaDAO;
import dao.CommentDAO;
import dao.SanPhamDAO;
import dto.HistoryBid;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import pojo.Chitietdaugia;
import pojo.Comment;
import pojo.Multimedia;
import pojo.Sanpham;
import pojo.Sanphammultimedia;
import pojo.Taikhoan;
import pojo.Thongtintaikhoan;

/**
 *
 * @author admin
 */
@WebServlet(name = "product", urlPatterns = {"/product.do"})
public class product extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }

        String urlView = "product.jsp";
        try {

            //Xet masp:
            if (request.getParameter("masp") == null) {
                response.sendRedirect("index.do");
                return;
            }
            int maSP = Integer.parseInt(request.getParameter("masp"));
            Sanpham sp = SanPhamDAO.LayChiTietSanPham(maSP);

            //Sản phẩm vừa xem
            HttpSession session = request.getSession();

            if (session.getAttribute("taiKhoan") != null) {
                Taikhoan tk = (Taikhoan) session.getAttribute("taiKhoan");
                boolean addedFavor = AjaxDAO.CheckFavor(sp.getMaSanPham(), tk.getMaTaiKhoan());
                request.setAttribute("favor", addedFavor);
            }

            ArrayList<Sanpham> listSPVuaXem = null;
            Object obj = session.getAttribute("SanPhamVuaXem");

            if (obj == null) {
                listSPVuaXem = new ArrayList<Sanpham>();
                session.setAttribute("SanPhamVuaXem", listSPVuaXem);
            } else {
                listSPVuaXem = (ArrayList<Sanpham>) obj;
            }

            for (int i = 0; i < listSPVuaXem.size(); i++) {
                Sanpham SP = listSPVuaXem.get(i);
                if (SP.getMaSanPham().equals(maSP)) {
                    listSPVuaXem.remove(i);
                    break;
                }
            }

            if (request.getParameter("bid") == null) {
                listSPVuaXem.add(sp);
                SanPhamDAO.capNhatSoLanXem(sp);
            } else {
                if (session.getAttribute("taiKhoan") == null) {
                    session.setAttribute("returnPage", request.getRequestURL() + "?" + request.getQueryString());

                    RequestDispatcher rd = request.getRequestDispatcher("login.do");
                    rd.forward(request, response);
                    return;
                }
                Taikhoan taiKhoan = (Taikhoan) session.getAttribute("taiKhoan");
                long bidMount = Long.parseLong(request.getParameter("bid_mount"));

                if (ChiTietDauGiaDAO.ThemChiTietDauGia(sp, taiKhoan, bidMount)) {
                    request.setAttribute("message", "Đặt giá thành công !");
                    sp = SanPhamDAO.LayChiTietSanPham(maSP);
                } else {
                    request.setAttribute("message", "Đặt giá thất bại !");
                }
            }

            if (request.getParameter("post_comment") != null) {
                String noiDungBL = request.getParameter("binhLuan").trim();
                Taikhoan taiKhoan = (Taikhoan) session.getAttribute("taiKhoan");

                if (CommentDAO.ThemBinhLuanMoi(sp, taiKhoan, noiDungBL) == true) {
                    request.setAttribute("message", "Bình luận của bạn đã được đăng thành công !");
                } else {
                    request.setAttribute("message", "Bình luận của bạn đăng thất bại !");
                }
            }

            //Lấy multimedia:
            Set<Sanphammultimedia> dsMultiPro = sp.getSanphammultimedias();
            ArrayList<Multimedia> dsMulti = new ArrayList<Multimedia>();
            if (dsMultiPro != null) {
                for (Iterator<Sanphammultimedia> it = dsMultiPro.iterator(); it.hasNext();) {
                    Sanphammultimedia mp = it.next();
                    dsMulti.add(mp.getMultimedia());
                }
            }

            //Lấy lịch sử giao dich:
            List<HistoryBid> listHitoryBid = AjaxDAO.GetHistoryList(maSP, 8);
            int tongLuotDauGia = AjaxDAO.TinhSoLuotDauGia(maSP);

            //Thông tin tài khoản:
            Thongtintaikhoan thongtinTK = (Thongtintaikhoan) sp.getTaikhoan().getThongtintaikhoans().toArray()[0];

            //Thông tin những phiên giao dịch của người bán:
            Set<Chitietdaugia> dsDauGiaTK = sp.getTaikhoan().getChitietdaugias();
            List<Chitietdaugia> dauGiaTK = new ArrayList<Chitietdaugia>(dsDauGiaTK);
            Collections.sort(dauGiaTK);
            if (dauGiaTK.size() >= 5) {
                dauGiaTK = dauGiaTK.subList(0, 5);
            } else {
                dauGiaTK = dauGiaTK.subList(0, dauGiaTK.size());
            }

            //Thông tin sản phẩm liên quan:
            List<Sanpham> spLienQuan = SanPhamDAO.laySanPhamLienQuan(maSP, sp.getDanhmuc());

            //Lấy thông tin bình luận:
            int tongBinhLuan = CommentDAO.TinhTongBinhLuan(maSP);
            int tongSoTrangBL = CommentDAO.TinhSoTrangHienThi(maSP, 5);
            int listTrang[] = new int[tongSoTrangBL];
            for (int i = 0; i < tongSoTrangBL; i++) {
                listTrang[i] = i + 1;
            }
            int trangHienTai = 1;
            if (request.getParameter("pagecm") != null) {
                trangHienTai = Integer.parseInt(request.getParameter("pagecm"));
            }
            List<Comment> dsBinhLuan = CommentDAO.LayBinhLuan(maSP, 5, trangHienTai);

            request.setAttribute("dsBinhLuan", dsBinhLuan);
            request.setAttribute("listTrang", listTrang);
            request.setAttribute("tongSoTrang", tongSoTrangBL);
            request.setAttribute("tongBinhLuan", tongBinhLuan);

            request.setAttribute("spLienQuan", spLienQuan);
            request.setAttribute("daugianguoiban", dauGiaTK);
            request.setAttribute("thongtinTK", thongtinTK);
            request.setAttribute("historyBid", listHitoryBid);
            request.setAttribute("tongluotDG", tongLuotDauGia);
            request.setAttribute("multimedia", dsMulti);
            request.setAttribute("sanpham", sp);
            request.setAttribute("num_favor", sp.getSanphamyeuthichs().size());

            RequestDispatcher rd = request.getRequestDispatcher(urlView);
            rd.forward(request, response);
            
        } catch (Exception ex) {
            response.sendRedirect("errorpage.do");

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
